<script setup lang="ts">
import { reactive, ref, toRaw } from "vue";
import { onUnload } from "@dcloudio/uni-app";
import { useEventChannel } from "@/hooks/page";
import { Toast } from "@/utils/toast";

import FormButton from "@/components/form/button.vue";

onUnload(() => eventChannel?.emit("ev-intro-edit", ""));

const inputValue = ref("");
const configData = reactive({
  placeholder: "",
  maxLength: 200,
});

const saveClick = () => {
  if (!inputValue.value) return Toast.show(configData.placeholder);
  eventChannel?.emit("ev-intro-edit", toRaw(inputValue.value));
};

const eventChannel = useEventChannel(() => {
  eventChannel.once("ev-intro-data", (resp) => {
    console.log("ev-intro-data", resp);

    uni.setNavigationBarTitle({ title: resp.title });
    inputValue.value = resp.value;
    configData.placeholder = resp.placeholder;
    if (resp.maxLength) configData.maxLength = resp.maxLength;
  });
});
</script>

<template>
  <view class="intro-form">
    <textarea
      class="intro-form-input"
      v-model="inputValue"
      auto-height
      :placeholder="configData.placeholder"
      :maxlength="configData.maxLength"
    />

    <view class="intro-form-limit">
      （{{ inputValue.length }}/{{ configData.maxLength }}）
    </view>
  </view>

  <view class="intro-btn">
    <view @click="saveClick">
      <FormButton :disabled="inputValue.length === 0">保存</FormButton>
    </view>
  </view>
</template>

<style lang="scss">
page {
  padding-top: 10rpx;
  background-color: #ffffff;
}

.intro-form {
  .intro-form-input {
    display: block;
    width: 100%;
    min-height: 100rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    font-size: 28rpx;
    color: #333333;
    line-height: 40rpx;
    box-sizing: border-box;
  }

  .intro-form-limit {
    padding-right: 30rpx;
    font-size: 24rpx;
    color: #c3c3c3;
    line-height: 34rpx;
    text-align: right;
    font-weight: bold;
  }
}

.intro-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 106rpx;
  padding: 14rpx 60rpx env(safe-area-inset-bottom);
  background-color: #ffffff;
}
</style>